<?php
namespace app\listener\admin;

use app\common\service\member\MemberAccountService;
use app\common\service\member\SettingService as MemberSetting;
use app\common\service\order\ShopOrderService;
use app\common\service\webscoket\CacheRedisService;
use app\job\OrderAssignJob;
use think\facade\Log;
use Swoole\Timer;
use think\facade\Queue;

class OrderAssignListener
{

    /**
     * 系统自动派单
     * @Author: 易军辉
     * @DateTime:2024-08-22 15:01
     * @param $event
     */
    public function handle($event): void
    {
        //系统派单
        $memberSetting  = MemberSetting::info('order_mode');
        if($memberSetting['order_mode']==1) {
            /********************当服务启动时判断队列是否有任务，没有清空一次缓存*****************************/
            if(Queue::size()<=0){
                $del_res = CacheRedisService::del('OrderAssignListener');
            }
            Timer::tick(1000 * 30, function () {
                Log::write("系统自动派单：" . date('Y-m-d H:i:s'));
                try {
                    $wait_account_num = MemberAccountService::getWaitAccountNum();
                    if($wait_account_num>0){
                        $cache_ids = CacheRedisService::sMembers('OrderAssignListener');
                        $list = ShopOrderService::getOrderAssigns($cache_ids);
                        if ($list) {
                            Log::write("推送订单数量：".count($list));
                            foreach ($list as $key => $val) {
                                CacheRedisService::sAdd('OrderAssignListener', $val['id']);
                                Queue::push(OrderAssignJob::class, $val);
                            }
                        }
                    }else{
                        Log::write("暂无可接单买家");
                    }
                } catch (\Exception $e) {
                    Log::error("系统自动派单错误：" . $e->getMessage());
                }
            });
        }
    }
}
